package consensus

import (
	"myPaxos/net"
	"myPaxos/helper"
	"github.com/spf13/viper"
	"fmt"
	"myPaxos/manager"
)

type Peer struct {
	proposer   *Proposer
	acceptor   *Acceptor
	transport  net.Transport
	viper      *viper.Viper
	eh         *manager.Eventhub
}

func NewPeer(transport net.Transport, eh *manager.Eventhub) *Peer {
	peer := &Peer{
		transport: transport,
		viper:     readConfig(),
		eh:        eh,
	}
	identities := helper.ResolveIdentity(peer.viper)
	id := peer.transport.GetSelfInfo().ID
	if identities[0] {
		peer.proposer = NewProposer(id,peer.viper)
	}
	if identities[1] {
		peer.acceptor = NewAcceptor()
	}
	return peer
}

const(
	Config_Home = "./configs/"
	Peer_Path  = "peer.toml"
)
func readConfig() *viper.Viper {
	viper := viper.New()
	viper.SetConfigType("toml")
	viper.SetConfigFile(Config_Home + Peer_Path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	return viper
}

func(peer *Peer) Start() {
	if peer.proposer != nil {
		peer.proposer.Start()
	}
}